package com.example.lenovo.demob;
//:学生列表部分

import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity implements IoDelStu {
    private ListView stulist;
    private Button addStu;
    private ArrayList<Student> students = new ArrayList<>();
    private StuAdapter stuAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setTitle("学生列表");

        //初始化适配器
        initAdapter();

        //添加学生
        AddStudents();

        //初始化ListView
        initListView();


        ReadFromDB();
    }

    /**
     * 初始化ListView
     */
    private void initListView() {
        stulist = findViewById(R.id.stulist);
        stulist.setAdapter(stuAdapter);
        stulist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int i, long id) {
                final Student student = students.get(i);
                Intent intent = new Intent();
                intent.putExtra("NO", student.getNo());
                intent.putExtra("NAME", student.getName());
                intent.putExtra("AGE", student.getAge());
                intent.putExtra("SEX", student.getSex());
                intent.setClass(MainActivity.this, EditStusActivity.class);
                startActivityForResult(intent, 1002);
            }
        });
    }

    /**
     * 初始化适配器
     */
    private void initAdapter() {
        stuAdapter = new StuAdapter(MainActivity.this, students, MainActivity.this);
    }

    /**
     * 添加学生
     */
    private void AddStudents() {
        addStu = findViewById(R.id.addStu);
        addStu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(MainActivity.this, AddStudentActivity.class);
                startActivityForResult(intent, 1001);
            }
        });
    }


    /**
     * 得到其他Activity返回的数据
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == 2001) {
            String no = data.getStringExtra("NO");
            String name = data.getStringExtra("NAME");
            int age = data.getIntExtra("AGE", 0);
            String sex = data.getStringExtra("SEX");
            Student student = new Student(no, name, age, sex);
            AddStusToDB(student);
        } else if (resultCode == 3001) {
            String no = data.getStringExtra("NO");
            String name = data.getStringExtra("NAME");
            int age = data.getIntExtra("AGE", 0);
            String sex = data.getStringExtra("SEX");
            Student student = new Student(no, name, age, sex);
            UpdateToDB(student);
        }

    }

    /**
     *   从数据库中更新数据
     */
    private void UpdateToDB(Student student) {
        Uri uri = Uri.parse("content://cn.gdcp.djy/student");
        String where="stuno='"+student.getNo()+"'";
        ContentValues contentValues=new ContentValues();
        contentValues.put("name",student.getName());
        contentValues.put("sex",student.getSex());
        contentValues.put("age",student.getAge());
        int rows=getContentResolver().update(uri,contentValues,where,null);
        Toast.makeText(MainActivity.this,"共更新了"+rows+"行",Toast.LENGTH_SHORT).show();
        this.sendBroadcast(new Intent("STU_HAD_UPDATE"));
        ReadFromDB();

    }

    /**
     * 添加学生到数据库
     */
    private void AddStusToDB(Student student) {
        Uri uri = Uri.parse("content://cn.gdcp.djy/student");
        ContentValues contentValues = new ContentValues();
        contentValues.put("stuno", student.getNo());
        contentValues.put("name", student.getName());
        contentValues.put("age", student.getAge());
        contentValues.put("sex", student.getSex());
        getContentResolver().insert(uri,contentValues);
        this.sendBroadcast(new Intent("STU_HAD_INSERT"));
        ReadFromDB();
    }

    /**
     * 从数据库中读取学生信息
     */
    private void ReadFromDB() {
        Uri uri = Uri.parse("content://cn.gdcp.djy/student");
        students.clear();
        Cursor cursor = getContentResolver().query(uri, null, null, null, null);
        if (cursor != null && cursor.getCount() > 0) {
            for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
                String no = cursor.getString(0);
                String name = cursor.getString(1);
                int age = cursor.getInt(2);
                String sex = cursor.getString(3);
                Student student = new Student(no, name, age, sex);
                students.add(student);
            }

        }

        stuAdapter.notifyDataSetChanged();
    }


    @Override
    public void del(Student student) {
        Uri uri = Uri.parse("content://cn.gdcp.djy/student");
        String where = "stuno='" + student.getNo() + "'";
        int rows=getContentResolver().delete(uri, where, null);
        Toast.makeText(MainActivity.this,"共删除了"+rows+"行",Toast.LENGTH_SHORT).show();
        this.sendBroadcast(new Intent("STU_HAD_DELETE"));
        ReadFromDB();
    }
}
